<template>
  <div class="black-red-import">
    <div v-show="!isShowExportDetail" class="export-list">
      <div class="search">
        <div class='fl'>
          <span class="icon-text" @click.stop="exportBlackRedList"><i class="iconfont icon-daoru"></i>导入</span>
          <span class="icon-text" @click.stop="refresh"><i class="iconfont icon-shuaxin"></i>刷新</span>
          <el-input
            placeholder="请输入批次号搜索"
            size="mini"
            class="condition"
            v-model="searchContent"
            @keyup.enter.native="searchByNum">
            <i
              class="el-input__icon el-icon-search"
              slot="suffix"
              @click="searchByNum">
            </i>
          </el-input>
        </div>
        <pagination class="page"
                    :small="true"
                    :currentPage="currentPage"
                    :count="count || 0"
                    :pageSize="pageSize"
                    :totalPage="totalPage"
                    @turnPage="turnPage">
        </pagination>
      </div>
      <div>
        <el-table
          class="table"
          :data="tableData">
          <el-table-column
            prop="batchNo"
            label="批次号">
          </el-table-column>
          <el-table-column
            prop="flagName"
            label="导入状态">
          </el-table-column>
          <el-table-column
            label="操作人">
            <template scope="scope">
              <agent
                :id="scope.row.creator"
                :isNum="true"
              ></agent>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="最后操作时间">
          </el-table-column>
          <el-table-column
            width="200"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" class="update-btn" size="small" @click="showExportDetail(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <left-slide :title="title" :visible.sync="isShowLeftSide" :showFooter="true" @cancelClick="close" @saveClick="lindInTem">
        <div class="import-main">
          <div class="btn-wrap">
            <el-button class="temp-download primary_btn">
              <a href="/static/template/blackRed_template.xlsx" download>下载导入模板</a>
            </el-button>
            <!--饿了么上传组件-->
            <el-upload style="display: inline-block;"
                       :action = "uploadUrl"
                       name = "upload"
                       accept = ".xls,.xlsx"
                       :data = "uploadHeaders"
                       :with-credentials = "true"
                       :on-success = "handleSuccess"
                       :before-upload = "beforeUpload"
                       :show-file-list = "false">
              <el-button class = "primary_btn" type="primary">选择导入文件</el-button>
            </el-upload>
            <span class="uploaded-file-name">{{fileMes.trueName}}</span>
          </div>
          <div class="tip-wrap">
            <p>温馨提示：</p>
            <p>1、支持后缀为xls和xlsx的Excel文件导入；</p>
            <p>2、填写号码时请填写正确的手机号码或固话号码，例：186xxxx9999或0108000xxxx；</p>
            <p>3、名单类型请填写红名单(0)、呼入黑名单(1)、外呼黑名单(2)；</p>
            <p>4、导入是异步处理的,提交导入后可以立刻进行其他的导入,服务器会排队处理；</p>
            <p>5、点击“刷新”导入任务列表，查看导入状态；</p>
            <p>6、导入字段若为空，则导入失败；</p>
          </div>
        </div>
      </left-slide>
    </div>
    <div class="export-detail" v-show="isShowExportDetail">
      <bread-crumb v-show="isShowExportDetail" :titleArr="titleArr" @back="goBack"></bread-crumb>
      <import-detail :batchNo="batchNo"></import-detail>
    </div>
  </div>
</template>
<script>
  import Agent from '@/components/public-modules/cache/Agent'
  import importDetail from './importDetail.vue'
  import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
  import Pagination from '@/components/public-modules/card/Pagination'
  import breadCrumb from '@/components/ui-modules/breadCrumb/BreadCrumbConfig.vue'
  import {deepClone, getDateNo} from '@/utils/m7Utils.js'
  export default {
    data () {
      return {
        title: '',
        tableData: [],
        oldPBX: '',
        disabledReload: true,   //  生效按钮是否能被点击
        searchContent: '',
        currentPage: 1,
        count: 0,
        pageSize: 10,
        isShowLeftSide: false,    //  展示上传窗口
        lastAllBlackRedList: [],
        titleArr: ['导入名单', '详情'],  //  面包屑
        isShowExportDetail: false,    //  展示导入批次详情
        uploadUrl: '/fileUpload',    //  上传相关
        uploadHeaders: {
          type: '',
          module: 'quickReply',
          sessionId: this.$store.state.session.sessionId
        },
        fileMes: {},    //  上传xls信息
        batchNo: ''    // 批次号
      }
    },
    methods: {
      //        隐藏导入详情列表
      goBack () {
          this.isShowExportDetail = false
      },
      //        展示导入详情列表
      showExportDetail (obj) {
        this.isShowExportDetail = true
        this.batchNo = obj.batchNo

      },
      // 关闭弹窗
      close () {
        this.isShowLeftSide = false
      },
//      查询导入批次列表
      search () {
        let data = {}
        data.pbx = this.PBX
        data.batchNo = this.searchContent
        data.page = this.currentPage
        data.limit = this.pageSize
        this.$store.dispatch('queryBlackRedImportTasks', data).then(resp => {
          if (resp && resp.success) {
            this.tableData = resp.list
            this.tableData.forEach(item => {
              if (item.flag === 'failure') {
                item.flagName = '失败'
              } else if (item.flag === 'finish') {
                item.flagName = '完成'
              } else {
                item.flagName = '解析中'
              }
            })
            this.count = resp.count
          } else {
            this.$message.error('查询失败！')
          }
        })
      },
       //   初始化
      init () {
        this.currentPage = 1
        this.searchContent = ''
        this.search()
      },
//      按批次号查询
      searchByNum () {
        this.currentPage = 1
        this.search()
      },
      turnPage (val) {
        this.currentPage = val
        this.search()
      },
//      打开导入上传窗口
      exportBlackRedList () {
        this.fileMes = {}
        this.title = this.$t('channelsettings.redBlack10')
        this.isShowLeftSide = true
      },
      refresh () {
        this.init()
      },
      reload (flag) { // 生效可以点击
        this.disabledReload = flag
      },
      active () {
        let obj = {}
        obj.PBX = this.PBX
        obj.Account = this.$store.state.session.account.account
        this.$store.dispatch('reloadIvr', obj).then(res => {
          if (res.success) {
            this.disabledReload = true
            this.$message({
              type: 'success',
              message: this.$t('configLazyLoad.process.effectiveSuccessfully')
            })
          }
        })
      },
      beforeUpload (file) {
        let arr = file.name.split('.')
        let arrType = ['xls', 'xlsx']
        if (arrType.indexOf(arr[arr.length - 1]) !== -1) {
          return true
        } else {
          this.$message.error(this.$t('sms.uploadFileWrong'))
          return false
        }
      },
//      上传成功
      handleSuccess (response, file, fileList) {
        let index = response.filePath.split('/').length - 1
        let data = {
          trueName: response.fileName,
          fileName: response.filePath.split('/')[index]
        }
        this.fileMes = deepClone(data)
        this.$store.dispatch('getBlackRedXlsHeads', data).then(res => {
          if (res.success) {
            this.fileMes.xlsHeads = res.heads
          }
        })
      },
//      导入确定按钮
      lindInTem () {
        let dateNo = getDateNo()
        let obj = {
          batchNo: dateNo,
          pbx: this.PBX
        }
        let data = Object.assign(obj, this.fileMes)
        this.$store.dispatch('blackRedListImport', data).then(res => {
          if (res.success) {
            this.$message.success('导入成功')
            this.close()
            this.init()
          }
        })
      }
    },
    components: {
      Agent,
      importDetail,
      breadCrumb,
      leftSlide,
      Pagination
    },
    watch: {
      PBX () {
        let routerName = this.$route.meta.title
        if (routerName === 'blackRedList') {
          this.init()
        }
      }
    },
    computed: {
      PBX () {
        return this.$store.state.config.callCenter.currentPBX
      },
      totalPage () {
        return Math.ceil(this.count / this.pageSize) || 1
      }
    },
    deactivated () {
      this.oldPBX = this.PBX
    },
//    通过pbx是否变化 决定是否初始化数据
    activated () {
      if (this.oldPBX !== this.PBX) {
        this.init()
      }
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .black-red-import
    .export-list
      padding 20px
    .uploaded-file-name
      color $c-main
      margin-top 14px
      display block
    .search
      height 30px
      padding 8px 10px
      border 1px solid #E7E7EB
      border-bottom none
      .el-icon-plus,.icon-shuaxin,.icon-fasongchenggong,.icon-reciguanli,.icon-daoru
        color $c-main
        font-size 12px
        margin-right 2px
      .disabled-icon
        color #9D9B9D
      .select
        margin-right 20px
      .condition
        width 270px
        margin-right 8px
      .page
        float right
      .icon-text
        margin-right 16px
        cursor pointer
        line-height 30px
      .disabled-text
        cursor not-allowed
    .table
      .update-btn
        cursor pointer
      .delete-btn
        cursor pointer
        color $c-pink
  .import-main
    padding 20px 20px 0
    .btn-wrap
      padding 40px
      .el-button
        margin-right 10px
  .tip-wrap
    padding 20px
    background-color rgba(246,246,246,1)
    border-radius 3px
    p
      color #3B5998
      font-size 12px
      padding 4px 0
</style>
